﻿//点击新增产品弹出显示
layui.use(['layer', 'form', 'table'], function () {
    var layer = layui.layer,
        form = layui.form,
        table = layui.table;
    var util = layui.util;
    var $ = layui.$;
    var dropdown = layui.dropdown;
    var laydate = layui.laydate;
    var colorpicker = layui.colorpicker;
    var selected = [];
    var datasadd = [];
    var selectedvalue = '';

    var token = localStorage.getItem("token");
    // 事件
    util.on('lay-on', {
        'test-page-new': function () {
            let selectedRows = [];
            //创建弹出层
            var index = layer.open({
                type: 1,
                title: '新增入库产品单',
                area: ['1300px', '500px'], // 宽高
                content: '<form class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px" >产品编码:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="productsCode" placeholder="产品编码" style="width:200px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px">产品名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="B" placeholder="产品名称" id="productsName" style="width:200px;" lay- affix="clear" class= "layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchBtn" > 查询</button>' +
                    '</div> ' +
                    '</form>' +
                    '<table class= "layui-table" id="Produrement-Id" >' +
                    '<thead>' +
                    '<tr>' +
                    '<th lay-data="{checkbox:true}" rowspan="2"></th>' +
                    '<col width="150">' +
                    '<col>' +
                    '</tr>' +
                    '</thead>' +
                    '</table>' +
                    '<button type="button" id="demo-login" class="layui-btn layui-bg-blue">提交</button>'
            });
            form.render();

            ////弹出层弹出时显示数据
            Getprocurement(1);
            //getProcurementList({
            //    productsCode: null,
            //    productsName: null,
            //    pageIndex: 1,
            //    pageSize: 10
            //});

            //查询
            $("#searchBtn").on('click', function () {
                var productsCode = $("#productsCode").val();
                var productsName = $("#productsName").val();
                Getprocurement(1);
                //getProcurementList({
                //    productsCode: productsCode,
                //    productsName: productsName,
                //    pageIndex: 1,
                //    pageSize: 10
                //});
            });

            //获取复选框的值
            table.on('checkbox(Produrement-Id)', function (obj) {
                console.log(obj);
                // 当前选中的行加入到 selectedRows 数组中
                if (obj.checked) {
                    selectedRows.push(obj.data);
                }
                else {
                    // 当前取消选中的行从 selectedRows 数组中移除
                    selectedRows = selectedRows.filter(row => row.productsID !== obj.data.productsID);
                }
                console.log(selectedRows)
            })

            //显示选中的产品信息(点击提交)
            $("#demo-login").on('click', function () {
                //关闭弹出层
                layer.close(index);
                var objs = {
                    Token: token,
                    pageIndex: 1,
                    pageSize: 1000,
                    StoreCode: '',
                    StoreName: '',
                    wid: ''
                }
                $.ajax({
                    url: "/Foundation/GetStorehouse",
                    type: "get",
                    data: objs,
                    success: function (d) {
                        var res = JSON.parse(d);
                        var supper = res.data.list;
                        console.log(supper);
                        var options = '<option value="">请选择库位</option>';
                        supper.forEach(function (item) {
                            options += '<option value="' + item.storehouseId + '">' + item.storehouseName + '</option>';
                        });
                        $('.city').html(options);
                        form.render('select');
                    },
                    error: function (xhr, status, error) {
                        console.log("新增出错: " + error);
                    }
                });
                //显示选中的产品
                table.render({
                    elem: "#ID-demo",
                    css: [
                        // 设置单元格样式
                        // 取消默认的溢出隐藏，并设置适当高度
                        '.layui-table-cell{height: 50px; line-height: 40px;}',
                        '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                        '.layui-table-cell select{height: 36px; padding: 0 5px;}',
                    ].join(''),
                    cols: [[
                        { type: 'checkbox' },
                        { field: 'productsName', title: '产品名称', width: 200 },
                        { field: 'productsCode', title: '产品编码', width: 200 },
                        { field: 'batch', title: '批次', width: 150, edit: 'text' },
                        { field: 'sprice', title: '单价', width: 150, edit: 'text' },
                        { field: 'quantity', title: '入库数', width: 150, edit: 'text' },
                        {
                            field: 'binlocation', title: '库位', minWidth: 120, templet: '#TPL-select'
                        },
                    ]],
                    data: selectedRows,
                    loading: true,

                    done: function (res, curr, count) {
                        var options = this;
                        table.on('edit(ID-demo)', function (obj) {
                            var value = obj.value; // 得到修改后的值
                            var data = obj.data; // 得到所在行所有键值
                            console.log(data);
                            var field = obj.field; // 得到字段
                        });

                        form.on('select(select-demo)', function (obj) {
                            selectedvalue = obj.value; // 获取选中项 value

                            table.on('checkbox(ID-demo)', function (obj) {
                                //当前选中的行加入到 selected 数组中
                                if (obj.checked) {
                                    var a = {
                                        "addName": "string",
                                        "addTime": "2024-12-02T06:04:18.564Z",
                                        "updName": "string",
                                        "updTime": "2024-12-02T06:04:18.564Z",
                                        "delName": "string",
                                        "delTime": "2024-12-02T06:04:18.564Z",
                                        "isDel": false,
                                        "stockId": 0,
                                        "productsID": obj.data.productsID,
                                        "batch": obj.data.batch,
                                        "sprice": obj.data.sprice,
                                        "quantity": obj.data.quantity,
                                        "binlocation": selectedvalue,
                                        "office_id": "string",
                                        "user_id": 0,
                                        "stateSP": 1
                                    };

                                    datasadd.push(a);
                                }
                                else {
                                    // 当前取消选中的行从 selected 数组中移除
                                    selected = selected.filter(row => row.productsID !== obj.data.productsID);
                                }
                                console.log(selected)
                            })
                        });
                        //获取复选框的值

                    }
                });

            })
        }
    });

    function Getprocurement(pageNum) {
        var dto = {
            Token: token,
            pindex: 1,
            psize: 10,
            ProcurementCode: $("#procurementCode").val() || '',
            ProductsCode: $("#productsCode").val() || '',
            ProductsName: $("#productsName").val() || '',
            ProcureState: $("#procureState").val() || '',
        };
        // 发送Ajax请求
        $.ajax({
            url: '/Procurement/GetProcurement',  // 这里填上你的后端接口地址
            type: 'get',
            data: dto,
            success: function (response) {
                var res = JSON.parse(response);
                console.log(res.data.list);
                if (res != null) {
                    // 渲染表格
                    table.render({
                        elem: '#Produrement-Id',
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'procurementCode', title: '订单号', width: 150, fixed: 'left', },
                            { field: 'productsName', title: '产品名称', width: 120 },
                            { field: 'productsCode', title: '产品编号', width: 120 },
                            { field: 'specs', title: '产品规格', width: 120 },
                            { field: 'storageUnits', title: '单位', width: 100 },
                            { field: 'price', title: '单价', width: 100 },
                            { field: 'procurementNum', title: '数量', width: 100 },
                        ]],
                        data: res.data.list,  // 数据源
                        limit: 10,    // 每页显示多少条数据
                        limits: [10, 20, 30],  // 分页选择项
                        curr: pageNum,  // 当前页
                        total: res.data.lcount,  // 总记录数
                        loading: true, // 启用加载状态
                    });

                    // 渲染分页控件
                    var totalPages = Math.ceil(res.lcount / 10);  // 计算总页数
                    layui.laypage.render({
                        elem: 'pagination',
                        count: res.lcount,  // 总记录数
                        limit: 10,
                        curr: pageNum,
                        jump: function (obj, first) {
                            if (!first) {
                                Getprocurement(obj.curr);  // 不为第一次调用时，重新渲染表格
                            }
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.log('请求失败: ' + error);
            }
        });

    }
    var inputElement = document.getElementById('vendorCode');
    var pysobj = [];
    inputElement.addEventListener('click', function (event) {
        if (event.detail === 2) { // 双击
            var indes = layer.open({
                type: 5,
                title: '选择供应商',
                area: ['1400px', '800px'],
                content: '<form class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" >供应商编号:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="VendorCode" placeholder="产品编码" style="width:180px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label">供应商名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="VendorName" placeholder="产品名称"  style="width:180px;" lay- affix="clear" class= "layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchBtns" style="margin-left: 50px;">查询</button>' +
                    '</div> ' +
                    '</form>' +
                    '<table class= "layui-table" id="vendor-Id" >' +
                    '<thead>' +
                    '<tr>' +
                    '<th lay-data="{checkbox:true}" rowspan="2"></th>' +
                    '<col width="150">' +
                    '<col>' +
                    '</tr>' +
                    '</thead>' +
                    '</table>' +
                    '<button type="button" id="demo-gysshows" class="layui-btn layui-bg-blue">提交</button>'


                ,
            });
            form.render();

            //弹出层弹出时显示数据
            getVendorList({
                VendorCode: null,
                VendorName: null,
                VendorType: null,
                Vphone: null,
                pageIndex: 1,
                pageSize: 20
            });

            //查询
            $("#searchBtns").on('click', function () {
                var VendorCode = $("#VendorCode").val();
                var VendorName = $("#VendorName").val();
                getVendorList({
                    VendorCode: VendorCode,
                    VendorName: VendorName,
                    VendorType: '',
                    Vphone: '',
                    pageIndex: 1,
                    pageSize: 20
                });
            });
            //获取复选框的值
            table.on('checkbox(vendor-Id)', function (obj) {
                console.log(obj);
                // 当前选中的行加入到 selectedRows 数组中
                pysobj.push(obj.data);
                console.log(pysobj)
            })
            //显示选中的供应商信息(点击提交)
            $("#demo-gysshows").on('click', function () {
                //关闭弹出层
                layer.close(indes);
                $("#vendorCode").val(pysobj[0].vendorCode);
                $("#vendorName").val(pysobj[0].vendorName);
                $("#vcontact").val(pysobj[0].vcontact);
                $("#vphone").val(pysobj[0].vphone);
            })
        } else { // 单击
            inputElement.readOnly = false;
            inputElement.focus();
        }
    });

    // 失去焦点时恢复只读状态
    inputElement.addEventListener('blur', function () {
        inputElement.readOnly = true;
    });
    //供应商显示
    function getVendorList({ VendorCode, VendorName, PageIndex = 1, pageSize = 20 }) {
        //获取查询条件
        let dtos = {
            VendorCode: VendorCode,
            VendorName: VendorName,
            VendorType: '',
            Vphone: '',
            PageIndex: 1,
            PageSize: 15,
            Token: localStorage.getItem("token")
        };
        $.ajax({
            url: "/Vendor/GetVendorShow",
            type: "get",
            data: dtos,
            success: function (d) {
                var res = JSON.parse(d);
                if (res != null && res.data) {
                    // 渲染表格
                    table.render({
                        elem: '#vendor-Id',
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'vendorCode', title: '供应商编码', width: 200, fixed: 'left', unresize: true },
                            { field: 'vendorName', title: '供应商名称', width: 200 },
                            { field: 'vphone', title: '电话', width: 150 },
                            { field: 'vfax', title: '传真', width: 150 },
                            { field: 'email', title: 'Email', width: 150 },
                            { field: 'vcontact', title: '联系人', width: 150 },
                            { field: 'vaddress', title: '地址', width: 150 }
                        ]],
                        data: res.data.list,  // 数据源
                        limit: 20,    // 每页显示多少条数据
                        limits: [10, 20, 30],  // 分页选择项
                        curr: 1,  // 当前页
                        total: res.data.listcount,  // 总记录数
                        loading: true, // 启用加载状态
                    });

                    // 渲染分页控件
                    layui.laypage.render({
                        elem: 'pagination',  // 分页容器
                        count: res.data.lcount,  // 总记录数
                        limit: pageSize,
                        jump: function (obj, first) {
                            if (!first) {
                                fetchVendorList({ VendorCode, VendorName, pageIndex: obj.curr, pageSize });  // 翻页时重新请求数据
                            }
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.log("查询出错: " + error);
            }
        });
    }
    $("#addpro").on('click', function () {
        //添加采购单
        var code = Math.floor(Math.random() * 1000000) + 100000;
        code = code.toString();
        var models = {
            "dto": {
                "stockCode": code,
                "stockOrderType": $("#stockOrderType").val(),
                "sorderNumber": $("#sorderNumber").val(),
                "vendorId": $("#vendorCode").val(),
                "vendorName": $("#vendorName").val(),
                "vendorContact": $("#vcontact").val(),
                "vendorPhone": $("#vphone").val(),
                "makePerson": $("#makePerson").val(),
                "markTime": $("#markTime").val(),
                "sRremark": $("#sRremark").val(),
                "office_id": "string",
                "user_id": 0,
                "addName": "string",
                "addTime": "2024-12-01T13:36:04.405Z",
                "stockProducts": datasadd
            }
        }
        models = JSON.stringify(models);
        console.log(models);
        $.ajax({
            url: "/EnterStorage/EnterStorageAdd",
            type: "post",
            data: {
                model: models,
                Token: token
            },
            success: function (d) {
                var res = JSON.parse(d);
                console.log(res);
                if (res != null) {
                    //添加成功                  
                    layer.msg('添加成功', { icon: 0 }, function () {
                        location.href = '/EnterStorage/EnterStorageShow';
                    });
                }
                else {
                    alert('添加失败');
                }
            }
        })
    })
});



